//
//  TDUserAccountViewModel.swift
//  微博
//
//  Created by tong dan on 16/3/7.
//  Copyright © 2016年 tong dan. All rights reserved.
//

import UIKit

class TDUserAccountViewModel: NSObject {
    
    // 视图模型引用的Model
    var account: TDUserAccount?
    
    var accessToken:String?{
    
    return account?.access_token
    
    }
    
    /// 以后,外界只需要调用这个属性就知道是否登录
    var isLogon: Bool {
        // account 不能为 nil && accessToken 不能过期
        if account != nil && isExpiresIn == false {
            // 代表当前用户登录
            return true
        }
        return false
    }
    
    /// 代表当前帐户是否过期 ,为 true 代表过期
    var isExpiresIn: Bool {
        //         当前时间比过期时间小,也就是还没到到过期时间,也就是没有过期
        if NSDate().compare(account!.expiresDate!) == .OrderedAscending {
            return false
        }
        return true
    }
    
    
    //全局访问点
    static let shareViewModel: TDUserAccountViewModel = {
        
        let viewModel = TDUserAccountViewModel()
        
        //会在第一次使用当前类的时候去从归档文件里面读取当前用户的信息
        viewModel.account = viewModel.userAccount()
        
        return viewModel
        
    }()
    
    //归档解档路径
    private var archivePath:String{
    return (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
    }
    
    
    //加载accessonToken
    func loadAccessToken(code:String,finished:(isSuccess:Bool)->()){
        
//        //请求地址
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//       
//        
//        //请求参数
//        
//        let params = [
//            
//            "client_id":WB_CLIENT_ID,
//            "client_secret":WB_CLIENT_SECRET,
//            "grant_type":"authorization_code",
//            "code":code,
//            "redirect_uri":WB_REDIRECT_URI
//            
//        ]
        
        //发送请求
        TDNetworkTools.sharedTools.loadAccessToken(code) { (response, error) -> () in
            if error != nil{
                
                print(error)
                return
        }

            
           
            //判断返回数据是否是字典
            guard let dict = response as? [String:AnyObject] else {
                
                print("返回的数据不是字典")
                
                //回调登录
                 finished(isSuccess: false)
                return
            }
            
            //字典转模型
            let account = TDUserAccount(dict: dict)
            print(account)
            
            //加载用户信息
            self.loadUserInfo(account, finished: finished)
        }
      
    }
    
    //请求用户信息
    private func loadUserInfo(account:TDUserAccount,finished:(isSuccess:Bool)->()){
//        
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        let params = [
//            
//            "access_token": account.access_token!,
//            "uid":account.uid!
//            
//        ]
        
        //发送请求
        TDNetworkTools.sharedTools.loadUserInfo(account.access_token!, uid: account.uid!) { (response, error) -> () in
            if error != nil {
                
                //错误信息可以不提示给用户，但是一定要在开发中输出
                print(error)
                finished(isSuccess: false)
                
                return
                
            }
            print(response)
            
            guard let dict = response as? [String: AnyObject] else {
                
                return
            }

        
        
        
            //取到用户的昵称与头像地址，设置到userAccount的模型中
            account.avatar_large = dict["avatar_large"] as? String
            account.screen_name = dict["screen_name"] as? String
            
            //保存数据的逻辑
            print(account)
            
            //归档保存
            self.saveUserAccount(account)
            
            //回调登录成功
            finished(isSuccess: true)
        }
    }
}

extension TDUserAccountViewModel{
    
    private func saveUserAccount(account:TDUserAccount){
        //1.获取归档路径
        print(archivePath)
        //2.NSKeyedArchiver
        NSKeyedArchiver.archiveRootObject(account, toFile: archivePath)
    }
    
    
        //解档数据
    func userAccount()->TDUserAccount?{
    
    
    return NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as?TDUserAccount
    
    }
}
